<?php
declare(strict_types=1);

namespace app\controller\user;

use app\controller\BaseController;
use app\model\Area;
use think\facade\Log;

class AreaController extends BaseController
{
    /**
     * 测试方法
     */
    public function test()
    {
        return json(['message' => 'AreaController is working']);
    }

    /**
     * 获取省市区树形结构
     */
    public function tree()
    {
        Log::info('Accessing tree method', [
            'request_uri' => request()->url(true),
            'path_info' => request()->pathinfo(),
            'controller' => request()->controller(),
            'action' => request()->action()
        ]);
        
        try {
            // 获取所有省份
            $provinces = Area::where('parent_id', 0)
                ->field('id, area_name as name')
                ->order('id', 'asc')
                ->select();

            if ($provinces->isEmpty()) {
                Log::info('No provinces found');
                return $this->success('获取成功', []);
            }

            // 获取省份下的城市和区县
            foreach ($provinces as &$province) {
                $cities = Area::where('parent_id', $province['id'])
                    ->field('id, area_name as name')
                    ->order('id', 'asc')
                    ->select();
                    
                foreach ($cities as &$city) {
                    $districts = Area::where('parent_id', $city['id'])
                        ->field('id, area_name as name')
                        ->order('id', 'asc')
                        ->select();
                    $city['children'] = $districts;
                }
                
                $province['children'] = $cities;
            }

            return $this->success('获取成功', $provinces);
            
        } catch (\Exception $e) {
            Log::error('Error in tree method', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return $this->error('获取失败：' . $e->getMessage());
        }
    }

    /**
     * 获取下级地区
     */
    public function children($id)
    {
        try {
            $areas = Area::where('parent_id', $id)
                ->field('id, area_name as name')
                ->order('id', 'asc')
                ->select();
                
            return $this->success('获取成功', $areas);
            
        } catch (\Exception $e) {
            return $this->error('获取失败：' . $e->getMessage());
        }
    }
} 